import yfieldsControls from "../yfieldsControls"

Component({
  properties: {
    rules: Object,
  },
  data: {
    form: {} as any,
    label: {} as any
  },
  relations: {
    '../yfieldsControls': {
      type: 'descendant', // 关联的目标节点应为子节点
      target: yfieldsControls,
      linked: function (target) {
        this.setData({ form: Object.assign(this.data.form, target.dataset) })
        let label = {} as any
        const labelName = Object.keys(target.dataset)[0]
        const laeblValue = target.data.label
        label[labelName] = laeblValue
        this.setData({ label: Object.assign(this.data.label, label) })
      }
    }
  },
  methods: {
    validate: function () {
      for (const key in this.data.rules) {
        // 判断form表单中是否存在这个数据
        if (!(key in this.data.form)) { return false; }
        const formValue = (this.data.form as any)[key]
        // 判断这个数据是否是required
        if (this.data.rules[key].require.value) {
          if (formValue == '') {
            const errMsg = this.data.rules[key].require.errMsg || `${this.data.label[key]}不能为空`
            wx.showToast({ title: errMsg, icon: "none" })
            return false
          }
        }
        // 判断这个数据的其他正则
        if (this.data.rules[key].re) {
          const re = new RegExp(this.data.rules[key].re.value)
          if (!re.test(formValue)) {
            const errMsg = this.data.rules[key].re.errMsg || this.data.label[key] + "匹配规则失败,未配置规则错误提示"
            wx.showToast({ title: errMsg, icon: "none" })
            return false
          }
        }
      }
      return true;
    },
    onSubmit: function () {
      if (!this.validate()) return;
      this.triggerEvent("onSubmit",this.data.form,{})
    },
  
  },
})